<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- <div>第四版手写Promise</div> -->
</body>
<script>
    // 2023.8.22
    let PENDING = 'pending'
    let FULFILLED = 'fulfilled'
    let REJECTED = 'rejected'
    class Promise4 {
        constructor(resolver) {
            this._result = undefined;
            this._state = PENDING;

            this._subscribers = []
            this._onFulfilledCallbacks = []
            // noop = () => {}
            // console.log('noop==', noop)
            // if (noop !== resolver) {
            //     resolver(resolve)
            // }
            console.log('resolver==', resolver)
            resolver(this.resolve)
        }
        // 接收异步操作返回的结果，并执依次执行注册的所有回调函数
        resolve = (value) => {
            this._result = value 
            this._state = FULFILLED
            setTimeout(() => {
                while (this._onFulfilledCallbacks.length > 0) {
                    this._onFulfilledCallbacks.shift()(this._result)
                }
            }, 0)
        }
        // 注册回调函数（观察者模式）
        then = (onFulfilled, onRejected) => {
            onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
            onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }

            const promise2 = new Promise4((resolve, reject) => {
                // 最难懂的代码部分
                let fulfilled = () => {
                    let x = onFulfilled(this._result)
                    x instanceof Promise4 ? x.then(resolve, reject) : resolve(x)
                }

                if (this._state === PENDING) {
                    this._onFulfilledCallbacks.push(fulfilled)
                } else if (this._state === FULFILLED) {
                    fulfilled()
                }
                console.log('this._state=', this._state, this._onFulfilledCallbacks[0])
            })
            return promise2
        }
    }
    // const pp = new Promise4((resolve) => {
    //     setTimeout(() => {
    //         resolve(44)
    //     }, 1000)
    // })
    // pp.then((res) => {
    //     console.log('pp.then我是注册的回调函数1', res)
    // }).then(res => {
    //     console.log('pp2.then我是注册的回调函数1', res)
    // })
    const tt = new Promise4((resolve) => {
        setTimeout(() => {
            resolve(55)
        }, 1000)
    }).then(res => {
        return new Promise4((resolve, reject) => {
            resolve(66)
        })
    }).then(res => {
        console.log('最后的then==', res)
    })
    const tt2 = async () => {
        console.log('4545')
    }
    console.log(tt instanceof Promise4)
    console.log(tt2() instanceof Promise)
</script>
</html>